<template>
    <el-dialog :model-value="props.EditRolesDialog" title="编辑角色" :before-close="() => emit('showRolesDialog', false)">
      <el-form ref="ruleFormRef" :model="form" label-width="auto" :rules="formRules.rules">
         <el-form-item label="角色名称" prop="roleName">
           <el-input v-model="form.roleName" disabled/>
         </el-form-item>
  
         <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="form.roleDesc"/>
         </el-form-item>
      </el-form>
  
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="emit('showRolesDialog', false)">取消</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref, watch } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { EditRoleFnc } from '@/api/roles'
  
    const props = defineProps({
      EditRolesDialog: {type: Boolean, required: true},
      row: {type: Object, required: true}
    })
  
    const emit = defineEmits(['showRolesDialog', 'init'])
    const ruleFormRef = ref<FormInstance>()
    const objForm = ref({}) // 复制对象  用做修改对象时做比较 是否有做修改  

    // 表单数据
    const form = reactive({ id: 0, roleName: '', roleDesc: '' })
    // 表单验证规则
    const formRules = reactive({
      rules: {
        roleDesc: [
          {required: true, message: '请填写角色描述', trigger: 'blur'},
          {min: 3, max: 10, message: '角色描述在3-10个字节', trigger: 'blur'}
        ]
      }
    })

    watch([() => props.row.roleID, () => props.row.roleName, () => props.row.roleDesc], async ([newID, newRoleName, newRoleDesc]) => {
      form.id = newID
      form.roleName = newRoleName
      form.roleDesc = newRoleDesc
      objForm.value = {...form}
    })

    // 提交表单
    const onSubmit = async (formEl: FormInstance | undefined) => {
      if(!formEl) return 
      await formEl.validate(async (valid) => {
        if(valid) {
          if(JSON.stringify(objForm.value) === JSON.stringify(form)) { // 未做修改
            emit('showRolesDialog', false)
          } else {
            const res = await EditRoleFnc(form.id, {
              roleName: form.roleName,
              roleDesc: form.roleDesc
            })
            if(res.data.meta.status === 200) {
              ElMessage({type: 'success', message: '更新成功', duration: 1000, onClose: () => {
                emit('showRolesDialog', false)
                emit('init')
              }})
            }
          }
        }
      }) 
    }
  </script>